import 'dart:async';

import 'package:flutter/cupertino.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/widgets.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
export 'package:pull_to_refresh/pull_to_refresh.dart';

class PrimaryRefresher extends StatelessWidget {
  final Widget child;
  final bool enablePullDown;
  final bool enablePullUp;
  final FutureOr<bool> Function() onRefresh;
  final FutureOr<bool> Function() onLoading;
  final RefreshController controller;
  final Axis scrollDirection;
  final bool reverse;
  final ScrollController scrollController;
  final bool primary;
  final ScrollPhysics physics;
  final double cacheExtent;
  final int semanticChildCount;
  final DragStartBehavior dragStartBehavior;
  final Color refreshColor;

  PrimaryRefresher({
    Key key,
    @required this.controller,
    this.child,
    this.enablePullDown: true,
    this.enablePullUp: true,
    this.onRefresh,
    this.onLoading,
    this.dragStartBehavior,
    this.primary,
    this.cacheExtent,
    this.semanticChildCount,
    this.reverse,
    this.physics,
    this.scrollDirection,
    this.scrollController,
    this.refreshColor,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return SmartRefresher(
      enablePullDown: enablePullDown,
      enablePullUp: enablePullUp,
      header: WaterDropHeader(
        complete: new Text("刷新成功", style: TextStyle(color: refreshColor)),
        failed: new Text("刷新失败请稍后再试一试", style: TextStyle(color: refreshColor)),
      ),
      footer: CustomFooter(
        builder: (BuildContext context, LoadStatus mode) {
          Widget body;
          if (mode == LoadStatus.idle) {
            body = Text("");
          } else if (mode == LoadStatus.loading) {
            body = CupertinoActivityIndicator();
          } else if (mode == LoadStatus.failed) {
            body = Text("加载失败！点击重试！");
          } else if (mode == LoadStatus.canLoading) {
            body = Text("松手,加载更多!");
          } else {
            body = Text("没有更多数据了!");
          }
          return Container(
            height: 55.0,
            child: Center(child: body),
          );
        },
      ),
      controller: controller,
      onRefresh: () async {
        bool result = await this.onRefresh();
        if (result)
          this.controller.refreshCompleted();
        else
          this.controller.refreshFailed();
        return result;
      },
      onLoading: () async {
        bool result = await this.onLoading();
        if (result)
          this.controller.loadComplete();
        else
          this.controller.loadFailed();
        return result;
      },
      child: child,
      scrollDirection: scrollDirection,
      reverse: reverse,
      scrollController: scrollController,
      primary: primary,
      physics: physics,
      cacheExtent: cacheExtent,
      semanticChildCount: semanticChildCount,
      dragStartBehavior: dragStartBehavior,
    );
  }
}